<?php 

	namespace App\Http\Controllers\Service;

	use App\Http\Controllers\Controller;
	//引入状态输出类
	use App\Models\M3Result;
	use Illuminate\Http\Request;
	use Redis;
	use App\Entity\Admin;
	use App\Entity\Chat;
	use App\Entity\Category;
	use App\Entity\Product;
	use App\Entity\PdtImages;
	use App\Entity\PdtContent;
	use App\Entity\OrderReal;
	use App\Entity\Index;
	/**
	* coder:zhengchengjun

	* time:2017-10-22

	* function:管理员控制器类

	*/

	class AdminController extends Controller{
		public $redis;
		public $imageBasePath='/data/wwwroot/default/laravel51/public';
		public function login(Request $request){
			$username=$request->input('username',' ');
			$password=$request->input('password',' ');
			$result=new M3Result();
			if(!$username||$username==' '||!$password||$password==' '){
				$result->status=0;
				$result->message='非法请求，请自行承担风险';
				return $result->toJson();
			}
			$memberInfo=Admin::where('username',$username)->first();
			if(!$memberInfo){
				$result->status=0;
				$result->message='用户不存在';
				return $result->toJson();
			}
			if(md5($password)!=$memberInfo->password){

				$result->status=0;

				$result->message="密码错误";

				return json_encode($result);

			}
			$result->status=1;

			$result->message='登录成功';

			$request->session()->put('Admin',$memberInfo->id);

			return json_encode($result);
		}
		//消息推送查询
		public function isMessage(){
			$chatDb=new Chat;
		 	$this->redis = new Redis();
        	$this->redis->connect('127.0.0.1', 6379);
        	//二维数组
        	$uid=$chatDb->select('customer')->get();
        	$userInfos=[];
        	foreach ($uid as $key => $value) {
				$status=$this->redis->get($value['customer'].'Status');
				if($status=='start'){
					$userInfo=$this->redis->get($value['customer']);
					array_push($userInfos,$userInfo);
				}
        	}
        	return json_encode($userInfos);
		}
		//添加分类
		public function addCategory(Request $request){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$category=new Category;
			$result=new M3Result;
			$name=$request->input('name');
			$parent_id=$request->input('parent_id','');
			if(!$name||$name==' '){
				$result->status=1;
				$result->message='分类名不能为空';
				return $result->toJson();
			}
			//判段是否重复
			if($category->where('name',$name)->pluck('id')){
				$result->status=1;
				$result->message='分类名不能重复';
				return $result->toJson();
			}
			//顶级分类
			if(!$parent_id){
				$category->name=$name;
				$category->save();
				$result->status=0;
				$result->message='添加成功';
				return $result->toJson();
				//二级分类
			}else{
				$category->name=$name;
				$category->parent_id=$parent_id;
				$category->save();
				$id=$category->id;
				$result->status=0;
				$result->message=$id;
				return $result->toJson();
			}
		}
		/**
		 * 缩略图方法
		 * @param  [type]  $filename  [图片文件路径]
		 * @param  [type]  $dest      [文件夹]
		 * @param  [type]  $dst_w     [缩略宽度]
		 * @param  [type]  $dst_h     [缩略高度]
		 * @param  string  $pre       [缩略图前缀]
		 * @param  boolean $delSource [是否删除原图]
		 * @return [type]             [不知道返回啥返回一个1‘嘻嘻’]
		*/
		public function thumb($filename,$dest=null,$dst_w=null,$dst_h=null,$delSource=false,$pre="thumb_"){
			$fileInfo=getimagesize($filename);
			list($src_w,$src_h,$imagetype)=$fileInfo;
			$mime=image_type_to_mime_type($imagetype);
			$createFrom=str_replace('/','createfrom',$mime);
			$outFun=str_replace('/','',$mime);
			//没有传目标宽高就让目标宽高等于图片文件的宽高
			if($dst_w==null){
				$dst_w=$src_w;
			}
			if($dst_h==null){
				$dst_h=$src_h;
			}
			$dst_image=imagecreatetruecolor($dst_h,$dst_h);
			//变量函数
			$src_image=$createFrom($filename);
			imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
			if($dest&&!file_exists($dest)){
				mkdir($dest,755,true);
			}
			$randNum=mt_rand(1000,9999);
			$midname=basename($filename);
			$dstName="{$pre}{$dst_w}X{$dst_h}_{$randNum}_{$midname}";
			$destination=$dest?$dest.'/'.$dstName:$dstName;
			$outFun($dst_image,$destination);
			imagedestroy($dst_image);
			imagedestroy($src_image);
			if($delSource){
				unlink($filename);
			}
			return $destination;
		}
		/**
		 * 判段上传文件是否为图片类型
		 * @param  [type]  $fileName [description]
		 * @return boolean           [description]
		 */
		public function isImage($fileName){
			//能得到相关信息，就代表是图片
			if(@getimagesize($fileName)){
				return true;
			}else{
				return false;
			}
		}
		/**
		 * 
		 * cid分类id
		 * @return [type] [description]
		 */
		public function uploadImage(Request $request,$cid=0,$option=0,$uptFlag=0,$uploadPath="zcjStore",$maxsize=2097152,$allowExt=array('jpeg','png','gif','jpg')){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$fileInfo = $_FILES['file'];
			$result=new M3Result;
			//上传错误
			if($fileInfo['error']!=0){
				switch ($fileInfo['error']) {
					case '1':
						$result->status=0;
						$result->message='上传文件超过了upload_max_filesize选项序设置的值';
						return $result->toJson();
					break;
				}
			}
			//判段上传的类型
			$ext=pathinfo($fileInfo['name'],PATHINFO_EXTENSION);
			//不允许的类型，你吃屎吧
			if(!in_array($ext,$allowExt)){
				$result->status=0;
				$result->message='上传文件类型非法';
				return $result->toJson();
			}
			//大于自定义大小的文件，给我去死
			if($fileInfo['size']>$maxsize){
				$result->status=0;
				$result->message='文件大于2m';
				return $result->toJson();
			}
			//检测服务端保存上传的临时文件是否是图片
			if(!$this->isImage($fileInfo['tmp_name'])){
				$result->status=0;
				$result->message='文件不是真实图片';
				return $result->toJson();
			}
			//检测服务端保存目录是否存在,不存在就创建
			if(!file_exists($uploadPath)){
				//不存在的操作,false
				mkdir($uploadPath,755,true);
			}
			//文件名拼上上传后缀名
			//这里不填参数了，微秒也以经够用了
			$uniName=uniqid().'.'.$ext;
			$destination=$uploadPath.'/'.$uniName;
			//把服务器端中的上传临时文件移动到指定目录
			if(!@move_uploaded_file($fileInfo['tmp_name'],$destination)){
				$result->status=0;
				$result->message='系统错误';
				return $result->toJson();
			}
			//分类图
			if(!$option){
				//把上传来的图片缩略并删除原图
				$destination=$this->thumb($destination,$uploadPath,200,200,true);
				$categoryDb=Category::find($cid);
				if($categoryDb->preview){
					unlink($this->imageBasePath.$categoryDb->preview);
				}
				$categoryDb->preview='/'.$destination;
				$categoryDb->save();
				$result->status=1;
				$result->message=$categoryDb->preview;
				return $result->toJson();
			}
			//商品略览图
			if($option==1){
				//把上传来的图片缩略并删除原图
				$productDb=Product::find($cid);
				if($productDb->preview){
					unlink($this->imageBasePath.$productDb->preview);
				}
				//在首页存在的商品要更改显示图信息
				if($productDb->indexFlag){
					$index=Index::find(8);
					$content=json_decode($index->content,true);
					foreach ($content as $key => $value) {
						if($value['id']==$cid){
							$content[$key]['preview']='/'.$destination;
							break;
						}
					}
					$index->content=json_encode($content);
					$index->save();
				}
				$productDb->preview='/'.$destination;
				$productDb->save();
				$result->status=1;
				$result->message=$productDb->preview;
				return $result->toJson();
			}
			//商品轮播图
			if($option==2){
				if($uptFlag){
					//修改就把他全部删除了
					$productImage=PdtImages::where('product_id',$cid)->get();
					if($productImage->toJson()!='[]'){	
						//删除路径
						foreach($productImage as $key=>$value){
							unlink($this->imageBasePath.$value->image_path);
						}
						PdtImages::where('product_id',$cid)->delete();
					}
				}
				$productImageDb=new PdtImages;
				if(count($productImageDb->where('product_id',$cid)->select('id')->get())>3){
					unlink($this->imageBasePath.'/'.$destination);
					$result->status=0;
					$result->message='只能上传4张轮播图';
					return $result->toJson();
				}
				$productImageDb->image_path='/'.$destination;
				$productImageDb->product_id=$cid;
				$productImageDb->save();
				$result->status=1;
				$result->message=$productImageDb->id;
				return $result->toJson();
			}
			//商品详情图
			if($option==3){
				$productContentDb=new PdtContent;
				//存在详情图
				if($productContentDb->where('product_id',$cid)->pluck('content')){
					//修改就是要把所有东西所有清空
					if($uptFlag){
						$imagearr=explode(',',$productContentDb->content);
						foreach ($imagearr as $key => $value) {
							@unlink($this->imageBasePath.$value);
						}
						$productContentDb=PdtContent::where('product_id',$cid)->first();
						$productContentDb->content='';
						$productContentDb->save();	
						$productContentDb->content='/'.$destination;
						$productContentDb->save();
						$result->status=1;
						$result->message='fsdf';
						return $result->toJson();				
					}else{
						//上面也是这样查出来的但就是不能保存我估记是一个数据对象只要用了select就不能保存了
						$productContentDb=PdtContent::where('product_id',$cid)->first();
						$content=$productContentDb->content;
						$productContentDb->content=$content.','.'/'.$destination;
						$productContentDb->save();
						$result->status=1;
						$result->message=$content;
						return $result->toJson();						
					}
				}else{
					$productContentDb=new PdtContent;
					$destination=$this->thumb($destination,$uploadPath,null,null,true);
					$productContentDb->product_id=$cid;
					$productContentDb->content='/'.$destination;
					$productContentDb->save();
					$result->status=1;
					$result->message=$productContentDb->id;
					return $result->toJson();
				}

			}
		}
		//删除分类
		public function deleteCategory(Request $request){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$didString=$request->input('del');
			$did=explode(',',$didString);
			$result=new M3Result;
			if(!$did){
				$result->status=1;
				$result->message='删除失败';				
				return $result->toJson();
			}
			if(Category::whereIn('id',$did)->delete()){
				$result->status=0;
				$result->message='删除成功';
				return $result->toJson();
			}else{
				$result->status=1;
				$result->message='删除失败';	
				return $result->toJson();
			}
		}
		/**
		 * 得到图片路径
		 * 写这个方法的原因呢，是因为上传插件不能得到返回的数据，所有我还要写一个接口来获取
		 * @return [type] [description]
		 */
		public function getUploadImgae($id,$opt=0){
			$result=new M3Result;
			//opt不存在就是得到分类图片路径
			if(!$opt){
				$categoryDb=Category::find($id);
				$preview=$categoryDb->preview;
				$result->status=0;
				$result->message=$preview;
				return $result->toJson();				
			}
			//得到商品略浏览图
			if($opt==1){
				$productDb=Product::find($id);
				$preview=$productDb->preview;
				$result->status=0;
				$result->message=$preview;
				return $result->toJson();	
			}
			//得到商品轮播图
			if($opt==2){
				$productImageDb=PdtImages::select('image_path')->where('product_id',$id)->orderBy('id','desc')->first();
				$preview=$productImageDb->image_path;
				$result->status=0;
				$result->message=$preview;
				return $result->toJson();	
			}
			//得到商品详情图
			if($opt==3){
				$productContentDb=new PdtContent;
				$productContentDb=$productContentDb->where('product_id',$id)->pluck('content');
				$arr=explode(',',$productContentDb);
				$result->status=0;
				$result->message=$arr[count($arr)-1];
				return $result->toJson();	
			}
		}
		/**
		 * 修改分类文字信息
		 * @return [type] [description]
		 */
		public function updCategory(Request $request,$cid){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$category=new Category;
			$result=new M3Result;
			$name=$request->input('name');
			$parent_id=$request->input('parent_id','');
			if(!$name||$name==' '){
				$result->status=1;
				$result->message='分类名不能为空';
				return $result->toJson();
			}
			$categoryDb=Category::find($cid);
			//当名字跟之前的不一样就是更改了名字
			//就要判段是否分类名是否重复了，如果跟之前的一样
			//那么就只是更改了父分类
			if($name!=$categoryDb->name){
				//判段是否重复
				if($category->where('name',$name)->pluck('id')){
					$result->status=1;
					$result->message='分类名不能重复';
					return $result->toJson();
				}
			}
			if(!$parent_id){	
				$categoryDb->name=$name;
				$categoryDb->save();
				$result->status=0;
				$result->message='修改分类文字信息成功';
				return $result->toJson();
				//父分类存在就是false
			}else{
				$categoryDb->name=$name;
				$categoryDb->parent_id=$parent_id;
				$categoryDb->save();
				$result->status=0;
				$result->message='修改分类文字信息成功';
				return $result->toJson();
			}
		}
		//添加商品
		public function addProduct(Request $request){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$productDb=new Product;
			$result=new M3Result;
			$name=$request->input('name','');
			$cid=$request->input('cid','');
			$summary=$request->input('summary','');
			$count=$request->input('count','');
			$price=$request->input('price','');
			if(!$name||!$summary||!$count||!$price){
				$result->message='不能有空的选项';
				$result->status=1;
				return $result->toJson();
			}
			//判段是否重复
			if($productDb->where('name',$name)->pluck('id')){
				$result->status=1;
				$result->message='商品名不能重复';
				return $result->toJson();
			}
			$specifications=$request->input('specifications','');
			if($specifications){
				$productDb->name=$name;
				$productDb->summary=$summary;
				$productDb->count=$count;
				$productDb->price=$price;
				$productDb->specifications=$specifications;
				$productDb->category_id=$cid;
				//推送到首页标识
				$indexFlag=$request->input('indexFlag','');
				if($indexFlag=="isRight"){
					$indexDb=Index::find(8);
					//json_decode是转对象啊，要加第二个参数才是转为数组
					$content=json_decode($indexDb->content,true);
					$productDb->indexFlag=1;
					$productDb->shopcount=0;
					$productDb->save();
					$test=$productDb->toJson();
					$test=json_decode($test,true);
					if($content){
						array_unshift($content,$test);
					//第一次的数据
					}else{
						$content[0]=$test;
					}
					$content=json_encode($content);
					$indexDb->content=$content;
					$indexDb->save();
				}else{
					$productDb->save();
				}
				$result->message=$productDb->id;
				$result->status=0;
				return $result->toJson();
			}else{
				$productDb->name=$name;
				$productDb->summary=$summary;
				$productDb->count=$count;
				$productDb->price=$price;
				$productDb->category_id=$cid;
				$productDb->save();
				$result->message=$productDb->id;
				$result->status=0;
				return $result->toJson();

			}
		}
		//删除商品
		public function deleteProduct(Request $request){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$didString=$request->input('del');
			$did=explode(',',$didString);
			//同步删除掉在首页推送的
			$index=Index::find(8);
			$content=$index->content;
			$content=json_decode($content,true);
			foreach ($content as $key=>$value) {
				if(in_array($value['id'],$did)){
					unset($content[$key]);
				}
			}
			$contentResult=[];
			foreach ($content as $key => $value) {
				array_push($contentResult,$value);
			}
			$index->content=json_encode($contentResult,true);
			$index->save();
			$result=new M3Result;
			if(!$did){
				$result->status=1;
				$result->message='删除失败';				
				return $result->toJson();
			}
			if(Product::whereIn('id',$did)->delete()){
				PdtContent::whereIn('product_id',$did)->delete();
				PdtImages::whereIn('product_id',$did)->delete();
				$result->status=0;
				$result->message='删除成功';
				return $result->toJson();
			}else{
				$result->status=1;
				$result->message='删除失败';	
				return $result->toJson();
			}
		}
		/**
		 * 修改商品
		 * @param  Request $request [description]
		 * @return [type]           [description]
		 */
		public function uptProduct(Request $request,$pid){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$productDb=Product::find($pid);
			$result=new M3Result;
			$name=$request->input('name','');
			$cid=$request->input('cid','');
			$summary=$request->input('summary','');
			$count=$request->input('count','');
			$price=$request->input('price','');
			if(!$name||!$summary||$count==''||!$price){
				$result->message='不能有空的选项';
				$result->status=1;
				return $result->toJson();
			}
			if($name!=$productDb->name){
				//判段商品名是否重复
				if($productDb->where('name',$name)->pluck('id')){
					$result->status=1;
					$result->message='分类名不能重复';
					return $result->toJson();
				}
			}
			$specifications=$request->input('specifications','');
			$indexFlag=$request->input('indexFlag',0);
			if($indexFlag){
				$indexFlag=1;
			}
			if($specifications){
				$productDb->indexFlag=$indexFlag;
				$productDb->name=$name;
				$productDb->summary=$summary;
				$productDb->count=$count;
				$productDb->price=$price;
				$productDb->specifications=$specifications;
				$productDb->category_id=$cid;
				$productDb->save();
				//不存在首页
				if(!$indexFlag){
					$index=Index::find(8);
					$content=json_decode($index->content,true);
					foreach ($content as $key => $value) {
						if($value['id']==$pid){
							unset($content[$key]);
							break;
						}
					}
					$contentResult=[];
					foreach ($content as $value) {
						array_push($contentResult,$value);
					}
					$index->content=json_encode($contentResult);
					$index->save();
				}else{
					//存在首页
					$indexDb=Index::find(8);
					//json_decode是转对象啊，要加第二个参数才是转为数组
					$content=json_decode($indexDb->content,true);
					$test=$productDb->toJson();
					$test=json_decode($test,true);
					array_unshift($content,$test);
					$content=json_encode($content);
					$indexDb->content=$content;
					$indexDb->save();
				}
				$result->message='修改成功';
				$result->status=0;
				return $result->toJson();
			}else{
				$productDb->indexFlag=$indexFlag;
				$productDb->name=$name;
				$productDb->summary=$summary;
				$productDb->count=$count;
				$productDb->price=$price;
				//false直接让他没
				$productDb->specifications='';
				$productDb->category_id=$cid;
				$productDb->indexFlag=$indexFlag;
				$productDb->save();
				//不存在首页
				if(!$indexFlag){
					$index=Index::find(8);
					$content=json_decode($index->content,true);
					foreach ($content as $key => $value) {
						if($value['id']==$pid){
							unset($content[$key]);
							break;
						}
					}
					$contentResult=[];
					foreach ($content as $value) {
						array_push($contentResult,$value);
					}
					$index->content=json_encode($contentResult);
					$index->save();
				}else{
					//存在首页
					$indexDb=Index::find(8);
					//json_decode是转对象啊，要加第二个参数才是转为数组
					$content=json_decode($indexDb->content,true);
					$test=$productDb->toJson();
					$test=json_decode($test,true);
					array_unshift($content,$test);
					$content=json_encode($content);
					$indexDb->content=$content;
					$indexDb->save();
				}
				$result->message='修改成功';
				$result->status=0;
				return $result->toJson();

			}

		}	
		public function addkuDi(Request $request,$oid){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$name=$request->input('name','');
			$code=$request->input('code','');
			$result=new M3Result;
			if(!$name||!$code){
				$result->status=1;
				$result->message='不能有空的选项';
				return $result->toJson();
			}
			$orderDb=OrderReal::find($oid);
			$orderDb->kuaidiInfo=$name.':'.$code;
			$orderDb->fahuoFlag=1;
			$orderDb->save();
			$result->status=0;
			$result->message='成功';
			return $result->toJson();
		}
		//pid只是一个位置索引
		public function deleteIndexProduct(Request $request,$pid){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$pid=explode(',',$pid);
			$index=Index::find(8);
			$content=json_decode($index->content,true);
			foreach ($pid as $value) {
				unset($content[$value]);
			}
			$contentResult=[];
			foreach ($content as $key => $value) {
				array_push($contentResult,$value);
			}
			$index->content=json_encode($contentResult);
			$index->save();
			//把商品的首页状态改为0
			Product::whereIn('id',$pid)->update(['indexFlag'=>0]);
			$result=new M3Result;
			$result->status=0;
			$result->message='删除成功';
			return $result->toJson();
		}
		public function adminMonResult(Request $request,$opt){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			switch ($opt) {
				case 1:
					//今日时间戳
					$beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
					$endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
					$result=OrderReal::where('orderStatus','<>',0)->whereBetween('creat_time_int',[$beginToday,$endToday])->simplePaginate(20);
				break;	
				//本月流水的条数
				case 2:
					$beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
					$endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
					$result=OrderReal::where('orderStatus','<>',0)->whereBetween('creat_time_int',[$beginThismonth,$endThismonth])->simplePaginate(20);						
				break;					
				//今年流水的条数
				case 3:
					$beginThisyear=mktime(0,0,0,1,1,date("Y")); 
					$endThisyear=mktime(23,59,59,12,31,date("Y"));
					$result=OrderReal::where('orderStatus','<>',0)->whereBetween('creat_time_int',[$beginThisyear,$endThisyear])->simplePaginate(20);						
				break;
			}
			return $result->toJson();
		}
		public function searchOrder(Request $request,$code){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$result=new M3Result;
			$id=OrderReal::where('ordercode',$code)->pluck('id');
			if(!$id){
				$result->status=1;
				$result->message='订单不存在';
				return $result->toJson();
			}else{
				$result->status=0;
				$result->message=$id;
				return $result->toJson();				
			}
		}
		public function orderResult(Request $request,$opt){
			if (!$request->session()->has('Admin')) {
				//回到后台登录页
				return redirect('/ssdfsdfpgospzz123adsf');
			}
			$orderrealDb=new OrderReal;
			if($opt==1){
				$result=$orderrealDb->select('id','total_price','orderStatus','phone','address','ps')->where('orderStatus',1)->where('fahuoFlag',0)->orderby('creat_time_int','desc')->simplePaginate(20);
				return $result->toJson();
			}
			//待收货订单
			//己付款己发货用户没有点确定收货订单没有完成
			if($opt==2){
				$result=$orderrealDb->select('id','total_price','orderStatus','phone','address','ps')->where('orderStatus',1)->where('fahuoFlag',1)->orderby('creat_time_int','desc')->simplePaginate(20);				
				return $result->toJson();
			}
			//己完成订单
			//己什款己收货的意思
			if($opt==3){
				$result=$orderrealDb->select('id','total_price','orderStatus','phone','address','ps')->where('orderStatus',2)->where('fahuoFlag',1)->orderby('creat_time_int','desc')->simplePaginate(20);				
				return $result->toJson();
			}
		}
		public function proResult(Request $request,$cid){
			$result=Product::where('category_id',$cid)->simplePaginate(20);
			return $result->toJson();
		}
	}

 ?>

